import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { VersioningType } from '@nestjs/common';
import * as session from 'express-session';
import { Cookie } from 'express-session';
import { Request, Response, NextFunction } from 'express';
import * as cors from 'cors';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { ResponseInterceptor } from './common/responseInterceptor';
import { ExceptionFilters } from './common/exceptionFilters';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { knife4jSetup } from 'nest-knife4j';
import { AuthGuard } from './auth/auth.guard';
import { JwtService } from '@nestjs/jwt';
import { RoleGuard } from './role/role.guard';

const whiteList = ['/captcha', '/upload/album'];

// 全局中间件
function GlobalMiddleWare(req: Request, res: Response, next: NextFunction) {
  console.log(req.originalUrl, 'req.originalUrl');
  // if (whiteList.includes(req.originalUrl)) {
  //     next()
  // } else {
  //     res.send({
  //         msg:'小黑子不能访问'
  //     })
  // }
  next();
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['error', 'warn'],
    cors: true,
  });
  // app.enableVersioning({
  //     type:VersioningType.URI
  // })
  app.use(cors());
  app.useStaticAssets(join(__dirname, '..', 'public'));
  // app.use(express.json())
  // app.use(express.urlencoded({extended: true}))
  app.use(GlobalMiddleWare);
  app.useGlobalFilters(new ExceptionFilters());
  app.useGlobalInterceptors(new ResponseInterceptor());
  app.useGlobalPipes(new ValidationPipe());
  app.use(session({ secret: 'zjj', rolling: true, name: 'zjj.sid' }));

  // const options = new DocumentBuilder()
  //   .addBearerAuth()
  //   .setTitle('nest-app')
  //   .setDescription('nest')
  //   .setVersion('1.0.0')
  //   .build();
  //
  // const document = SwaggerModule.createDocument(app, options);
  // SwaggerModule.setup('/doc', app, document, {
  //   // 自定义样式
  //   customCssUrl: '/css/theme-material.css',
  // });

  const options = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document, {
    customCssUrl: '/css/theme-outline.css',
  });
  knife4jSetup(app, [
    {
      name: '2.X版本',
      url: `/api-json`,
      swaggerVersion: '2.0',
      location: `/api-json`,
    },
  ]);
  app.useGlobalGuards(new AuthGuard(new JwtService(), new Reflector()));
  // app.useGlobalGuards(new RoleGuard(new Reflector()));
  await app.listen(3000);
}

// 守卫是在中间件之后，所有拦截器或者管道之前执行
bootstrap();
